package com.honsen.yangban;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.appcompat.widget.AppCompatButton;

/**
 * 带水波纹效果的按钮
 */
public class RippleButton extends AppCompatButton {
    private Paint ripplePaint = new Paint();
    private RadialGradient radialGradient;
    //递增的半径
    private float radius = -1;
    private float currentX;
    private float currentY;

    public RippleButton(Context context) {
        this(context, null);
    }

    public RippleButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        ripplePaint.setAntiAlias(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                //记录手抬起的点
                currentX = event.getX();
                currentY = event.getY();
                radius = 1;
                //通知重绘
                postInvalidate();
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (radius > 0 && radius < getMeasuredWidth()) {
            radialGradient = new RadialGradient(currentX, currentY, radius, Color.BLUE, Color.TRANSPARENT, Shader.TileMode.CLAMP);
            ripplePaint.setShader(radialGradient);

            canvas.drawCircle(currentX, currentY, radius, ripplePaint);

            postInvalidateDelayed(5);

            radius += 20;
        } else {
            radius = -10;
        }
    }
}
